import Vue from 'vue'
import store from "@/store"

// 跳转
function navTo(e) {
	uni.navigateTo({
		url: e
	})
}

// 跳转判断token
function navToLogin(e) {
	if(store.state.token) {
		uni.navigateTo({
			url: e
		})
	} else {
		uni.showModal({
			title: '提示',
			content: '暂未登录',
			confirmText: "去登录",
			confirmColor: "#5A68FF",
			success: function (res) {
				if (res.confirm) {
					uni.switchTab({
						url: "/pages/wo/index"
					})
				}
			}
		})
	}
}

// 微信支付
function getOrder(id) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '请求支付中...',
			mask:true,
		})
		var params = {
			order_id: id
		}
		Vue.prototype.$httpApi.wxPay(params).then((res) => {
			uni.hideLoading()
			if (res.code == 1) {
				uni.requestPayment({
					provider: 'wxpay',
					...res.data,
					success(payres) {
						// console.log(payres)
						resolve()
					},
					fail(error) {
						uni.showToast({
							title: '支付失败',
							icon:'none',
							mask:true,
						})
					}
				})
			}
		})
		
	})
}

// 登录
function getLogin() {
	uni.login({
		success: function(wxres) {
			var key = uni.getStorageSync('invitecode')
			var params = {
				code: wxres.code
			}
			if(key) {
				params.pid = key
			}
			Vue.prototype.$httpApi.reglogin(params).then((res) => {
				uni.hideLoading()
				if (res.code == 1) {
					// 储藏token
					store.commit('SET_TOKEN', res.data.userinfo.token)
					// 储藏库管
					store.commit('SET_ADMIN', res.data.userinfo.is_admin)
					// 获取个人信息
					store.dispatch('getUserInfo')
					// 清除绑定
					if(key) {
						uni.removeStorageSync('invitecode')
					}
				}
			})
		}
	})
}

export default {
	install(Vue) {
		Vue.prototype.$navTo = (e) => navTo(e)
		Vue.prototype.$navToLogin = (e) => navToLogin(e)
		Vue.prototype.$getOrder = (e) => getOrder(e)
		Vue.prototype.$getLogin = (e) => getLogin(e)
	}
}